#include <iostream>
#include <thread>
#include <string>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>

int sockfd;

void receive_loop() {
    char buf[1024];
    while (true) {
        int len = recv(sockfd, buf, sizeof(buf) - 1, 0);
        if (len > 0) {
            buf[len] = '\0';
            std::cout << buf;
        } else if (len == 0) {
            std::cout << "[Client] Server closed the connection.\n";
            break;
        } else {
            std::cerr << "[Client] recv() error.\n";
            break;
        }
    }
    shutdown(sockfd, SHUT_RDWR);
    close(sockfd);
    exit(0);
}

int main() {
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd == -1) {
        std::cerr << "Failed to create socket\n";
        return 1;
    }

    sockaddr_in serv_addr{};
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(6666);
    serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");

    if (connect(sockfd, (sockaddr*)&serv_addr, sizeof(serv_addr)) == -1) {
        std::cerr << "Failed to connect to server\n";
        return 1;
    }

    std::thread recv_thread(receive_loop);

    std::string line;
    while (std::getline(std::cin, line)) {
        send(sockfd, line.c_str(), line.size(), 0);
    }

    recv_thread.join();
    return 0;
}

